package com.kt.controller;

import com.kt.pojo.Admin;
import com.kt.pojo.AdminLoginParam;
import com.kt.pojo.RespBean;
import com.kt.pojo.Role;
import com.kt.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;

/**
 * @author KamTeng
 * @date 2021/2/22 15:21
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Resource
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回的Token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
        return adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(), adminLoginParam.getCode(), request);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        if (principal != null) {
            String username = principal.getName();
            Admin admin = adminService.getAdminByUserName(username);
            admin.setPassword(null);
            admin.setRoles(adminService.getRoles(admin.getId()));
            return admin;
        }
        return null;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功!");
    }

    @ApiOperation(value = "根据用户id获取角色")
    @GetMapping("/admin/roles")
    public List<Role> getRoleById(Principal principal) {
        String username = principal.getName();
        Admin adminByUserName = adminService.getAdminByUserName(username);
        return adminService.getRoles(adminByUserName.getId());
    }
}
